<?php
namespace cms\modules\v1\models\userFund;

use cms\modules\v1\models\prop\PropInfo;
use cms\modules\v1\models\user\User;
use common\models\Functions;
use common\models\prop\PropWarehouseChangeLog;
use common\models\Status;
use common\models\userFund\UserRechargeOrder;
use Yii;
use yii\base\Exception;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class RechargeOrder extends UserRechargeOrder
{

    /**
     * 返回列表数据
     * @param int $page
     * @param int $size
     * @return array
     */
    public function getListData($page = 1, $size = 20) {
        try {

            //搜索条件
            $searchWhere  = $this->getSearch();//自定义搜索条件

            //得到文章的总数
            $count = self::getCountByAndWhere($searchWhere['where'], $searchWhere['andWhere']);
            $data = static::setPageinationAPI($page, $size, $count);
            $offset = ($page - 1) * $size;

            //排序 order
            $orderSql = 'id DESC';

            $list = static::getObjectByAndWhere($searchWhere['where'],$searchWhere['andWhere'], '*', $orderSql, $offset, $size);

            $data['data'] = $this->handelList($list);

            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 自定义参数的搜索  搜索,搜索也分每一列
     * 这里要根据业务逻辑进行修改
     * @return array
     */
    public function getSearch () {
        $where = [];
        $andWhere = [];
//        if(isset($status) && !empty($status)) {
//            $where['status'] = $status;
//        }
//        $status = isset($search['status']) ? $search['status'] : '';
        $status = Yii::$app->request->get('status',0);
        $type = Yii::$app->request->get('type',0);
        $orderNumber = Yii::$app->request->get('order_number','');
        $loginName = Yii::$app->request->get('login_name','');
        $startTime = Yii::$app->request->get('start','');
        $endTime = Yii::$app->request->get('end','');

        if($status) {
            $where['status'] = (int) $status;
        }

        if($type) {
            $where['type'] = (int) $type;
        }


        if($orderNumber) {
            $where['order_number'] = $orderNumber;
        }

        if($loginName) {
            $userId = User::searchByName($loginName);
            $where['user_id'] = $userId;
        }

        if(!empty($startTime) && empty($endTime)) {
            $andWhere = ['>','create_time',$startTime. ' 00:00:00'];
        } elseif(empty($startTime) && !empty($endTime)) {
            $andWhere = ['<','create_time',$endTime. ' 23:59:59'];
        } elseif (!empty($startTime) && !empty($endTime)) {
            $andWhere = ['between','create_time',$startTime. ' 00:00:00', $endTime. ' 23:59:59'];
        }

        return [
            'where' => $where,
            'andWhere' => $andWhere
        ];
    }

    /**
     * 处理初始化数据
     * @param $query
     * @return mixed
     */
    public function handelList($query) {
        if (empty($query)) {
            return null;
        }

        $list = $query->with([
            'user' => function ($q) {
                $q->select(['id','login_name','user_face','nick_name','tx_code','user_code']);
            },

        ])->asArray()->all();

        foreach($list as &$value) {
            $singleUser = ArrayHelper::getValue($value,'user',[]);
            $value['user_phone'] = $singleUser['login_name'] ?? '';
            $value['money'] = floatval($value['money']);
            $value['type_name'] = Status::PAY_WAY_MAP[$value['pay_way']] ?? '';
            $value['status_name'] = Status::RECHARGE_STATUS_MAP[$value['status']] ?? '';
        }
        return $list;
    }

    /**
     * 后台充值
     * @return array
     */
    public function add() {
        $post = Yii::$app->request->post();
        $tabName = trim($post['tabName']);
        switch ($tabName) {
            case 'money':
                return $this->addRecharge();
                break;

//            case 'freedomMoney':
//                return (new UserFreedomMoneyLog()) -> addFreedomMoney();
//                break;
//            case 'card' :
//                return (new UserVipCardLog()) -> addVipCard();
//                break;
        }
    }

    /**
     * 后台充值
     * @return array
     */
    public function addRecharge() {
        $post = Yii::$app->request->post();
        $money = floatval($post['money']);
        $mark = Yii::$app->request->post('mark','');
        $type = Yii::$app->request->post('type',0);
        $userId = intval($post['id']);

        $trans = Yii::$app->db->beginTransaction();

        try {

            if($money == 0) {
                throw new Exception('充值金额有误');
            }

            if(!$userId) {
                throw new Exception('充值用户错误');
            }

            if(!$type) {
                throw new Exception('请选择充值内容');
            }



            $trans->commit();

            return Functions::formatRestAPI(0, '充值成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }


}
